package tree.MergeTreeNode;

import tree.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @ClassName MergeTreeNode
 * @Description TODO
 * @Author lenovo
 * @Date 2023-03-29 10:02
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class MergeTreeNode {

    //   2       3                    5
    // 2   1   2                   4    1

    /**
     * 给你两棵二叉树： root1 和 root2 。
     * <p>
     * 想象一下，当你将其中一棵覆盖到另一棵之上时，两棵树上的一些节点将会重叠（而另一些不会）。你需要将这两棵树合并成一棵新二叉树。合并的规则是：如果两个节点重叠，那么将这两个节点的值相加作为合并后节点的新值；否则，不为 null 的节点将直接作为新二叉树的节点。
     * <p>
     * 返回合并后的二叉树。
     * <p>
     * 注意: 合并过程必须从两个树的根节点开始。
     *
     * @param root1
     * @param root2
     * @return
     */
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if (root1 == null) return root2;
        if (root2 == null) return root1;

        Queue<TreeNode> queue = new LinkedList<>();

        queue.add(root1);
        queue.add(root2);

        while (!queue.isEmpty()) {
            TreeNode poll1 = queue.poll();
            TreeNode poll2 = queue.poll();
            poll1.val = poll1.val + poll2.val;
            if (poll1.left != null && poll2.left != null) {
                queue.add(poll1.left);
                queue.add(poll2.left);
            }

            if (poll1.right != null && poll2.right != null) {
                queue.add(poll1.right);
                queue.add(poll2.right);
            }

            if (poll1.left == null && poll2.left != null) {
                poll1.left = poll2.left;
            }

            if (poll1.right == null && poll2.right != null) {
                poll1.right = poll2.right;
            }

        }
        return root1;
    }

    //   2       3                    5
    // 2   1   2                   4    1
    public TreeNode mergeTrees1(TreeNode root1, TreeNode root2) {
        if (root1 == null) return root2;
        if (root2 == null) return root1;

        root1.val = root1.val + root2.val;
        root1.left = mergeTrees1(root1.left, root2.left);
        root2.right = mergeTrees1(root1.right, root2.right);
        return root1;
    }

    public static void main(String[] args) {
        TreeNode tree1 = new TreeNode(2);
        TreeNode tree2 = new TreeNode(3);
        TreeNode left1 = new TreeNode(2);
        tree1.left = left1;
        TreeNode right2 = new TreeNode(1);

        tree1.right = right2;

        TreeNode left2 = new TreeNode(2);

        tree2.left = left2;
        MergeTreeNode mergeTreeNode = new MergeTreeNode();
        System.out.println(mergeTreeNode.mergeTrees1(tree1, tree2));
    }
}